package com.yun.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yun.reggie.common.BaseContext;
import com.yun.reggie.common.R;
import com.yun.reggie.entity.ShoppingCart;
import com.yun.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author xiao
 */
@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @GetMapping("/list")
    public R<List<ShoppingCart>> list(HttpSession session){
        //获取用户id
        Long userId = (Long)session.getAttribute("user");
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(userId != null,ShoppingCart::getUserId,userId)
                .orderByAsc(ShoppingCart::getCreateTime);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(wrapper);
        return R.success(shoppingCarts);
    }

    /**
     *  套餐数据
     *  ShoppingCart(id=null, name=狗屎拌饭, userId=null, dishId=null, setmealId=1637782260306448385,
     *  dishFlavor=null, number=null, amount=250, image=9773fb42-3ff5-465a-b666-110d7d21ff13.jpg, createTime=null)
     *  菜品数据
     *  ShoppingCart(id=null, name=全家福, userId=null, dishId=1397851099502260226, setmealId=null,
     *  dishFlavor=不要辣,中辣, number=null, amount=118, image=a53a4e6a-3b83-4044-87f9-9d49b30a8fdc.jpg, createTime=null)
     *
     *  如果是添加同一份食物，就在原先基础上number+1
     * @param shoppingCart
     * @return 这里需要传回添加的对象，用于显示
     */
    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart, HttpSession session){
        Long userId = (Long)session.getAttribute("user");
        if (userId == null){
            return R.error("用户未登录！");
        }
        //查询是否有相同的食物(userId相同，dishId/setmealId相同)
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(userId != null,ShoppingCart::getUserId,userId)
                .eq(shoppingCart.getDishId() != null,ShoppingCart::getDishId,shoppingCart.getDishId())
                .eq(shoppingCart.getSetmealId() != null,ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        ShoppingCart one = shoppingCartService.getOne(wrapper);
        if (one == null){
            //说明购物车中没有此类食物
            //设置购物车所属的用户id
            shoppingCart.setUserId(userId);
            //设置number 份数
            shoppingCart.setNumber(1);
            //设置创建时间
            shoppingCart.setCreateTime(LocalDateTime.now());
            //无论是套餐还是菜品，都添加
            shoppingCartService.save(shoppingCart);
            //保存完之后，会返回给原对象，需要重传回前端显示
            one = shoppingCart;
        }else {
            //已经有了，修改number
            one.setNumber(one.getNumber()+1);
            shoppingCartService.updateById(one);
        }
        return R.success(one);
    }

    /**
     * "dishId":null,"setmealId":"1637782260306448385"
     * 点击购物车的减号，减少份数
     * @param shoppingCart
     * @return
     */
    @PostMapping("sub")
    public R<ShoppingCart> sub(@RequestBody ShoppingCart shoppingCart){
        //既可以通过session获取，也可以通过自定义的ThreadLocal的工具封装类，在一个线程范围内获取id
        Long userId = BaseContext.getCurrentId();
        //先根据id查询对应食物
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(userId != null,ShoppingCart::getUserId,userId)
                .eq(shoppingCart.getDishId() != null,ShoppingCart::getDishId,shoppingCart.getDishId())
                .eq(shoppingCart.getSetmealId() != null,ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        ShoppingCart one = shoppingCartService.getOne(wrapper);
        //首先，数据库中有，才会在前端显示，所以正常情况下查询的one一定不为null，至少还有一份
        if (one.getNumber() == 1){
            //如果还剩一份,则删除
            shoppingCartService.removeById(one.getId());
            //因为删除了，但是不会返回结果给原先的对象one.需要把值设置为0，重传回前端。
            //不能返回one=null，因为前端使用的是v-if，有值才改变。传回的是null，那就会保持原样不改变(导致数量一直是1)
            one.setNumber(0);
        }else {
            //否则number--
            one.setNumber(one.getNumber()-1);
            shoppingCartService.updateById(one);
        }
        return R.success(one);
    }

    @DeleteMapping("/clean")
    public R<String> cleanAll(){
        //清除所有关于当前用户的购物信息
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(userId != null,ShoppingCart::getUserId,userId);
        shoppingCartService.remove(wrapper);
        return R.success("清除成功！");
    }
}
